﻿using Entities;
using Interfaces;
using Microsoft.Extensions.Caching.Memory;

namespace ProductService.Services
{
    public class TagService(IMemoryCache cache, IRepository<Tag, long> repository)
    {
        private const string TAGS_KEY = "tags";

        /// <summary>
        /// Get all tags from the database and cache them for 1 hour.
        /// </summary>
        /// <returns></returns>
        public async Task<List<Tag>> GetTagsAsync()
        {
            return await cache.GetOrCreateAsync(TAGS_KEY, async entry =>
            {
                entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1);
                return await repository.ToListAsync(repository.AsNoTracking());
            }) ?? [];
        }


        /// <summary>
        /// 验证标签是否存在
        /// </summary>
        public async Task<bool> AreValidTagsAsync(List<string> slugs)
        {
            var tags = await GetTagsAsync();
            var tagSet = new HashSet<string>(tags.Select(t => t.Slug));
            return slugs.All(tagSet.Contains);
        }
    }
}
